import { Popup as NutuiPopup, SafeArea } from '@nutui/nutui-react-taro';
import { View } from '@tarojs/components';
import type { ReactNode, ForwardRefRenderFunction } from 'react';
import React, {
  useImperativeHandle,
  useState,
  forwardRef,
  useRef,
} from 'react';
import './index.scss';
import type { PopupProps as NutuiPopupProps } from '@nutui/nutui-react-taro/dist/types/packages/popup/popup.taro';
import type { PropsWithChildren } from 'react';

export interface PopupRef {
  open: () => void;
  close: () => void;
  toggle: () => void;
}

const PREFIX_CLS = 'm-custom-popup';

interface PopupProps extends PropsWithChildren<Partial<NutuiPopupProps>> {
  footer?: ReactNode;
  content?: ReactNode; // 弹窗内容
  className?: string;
  style?: React.CSSProperties;
  showSafeArea?: boolean;
}

const Popup: ForwardRefRenderFunction<PopupRef, PopupProps> = (
  {
    footer,
    content,
    children,
    className,
    style,
    onClose,
    position = 'bottom',
    showSafeArea = true,
    ...rest
  },
  ref,
) => {
  const [visible, setVisible] = useState(false);
  const [renderKey, setRenderKey] = useState(0);
  const isProgrammaticCloseRef = useRef(false);

  useImperativeHandle(ref, () => ({
    open: () => {
      isProgrammaticCloseRef.current = false;
      setVisible(true);
      setRenderKey((prev) => prev + 1);
    },
    close: () => {
      isProgrammaticCloseRef.current = true;
      setVisible(false);
      setRenderKey((prev) => prev + 1);
      // 立即调用 onClose，不等 NutuiPopup 的 onClose
      onClose?.();
    },
    toggle: () => {
      setVisible((prev) => !prev);
      setRenderKey((prev) => prev + 1);
    },
  }));

  const handleClose = () => {
    // 如果是程序主动关闭的，不要重复处理
    if (isProgrammaticCloseRef.current) {
      isProgrammaticCloseRef.current = false;
      return;
    }
    isProgrammaticCloseRef.current = true;
    setVisible(false);
    setRenderKey((prev) => prev + 1);
    onClose?.();
    // 短暂延迟后重置标记，防止立即被 toggle 打开
    setTimeout(() => {
      isProgrammaticCloseRef.current = false;
    }, 300);
  };

  const handleToggle = (e: any) => {
    e.stopPropagation();
    // 如果正在关闭过程中，忽略 toggle 操作
    // if (isProgrammaticCloseRef.current) {
    //   console.log('Toggle blocked - popup is closing');
    //   return;
    // }
    setVisible((prev) => !prev);
    setRenderKey((prev) => prev + 1);
  };

  return (
    <>
      <View onClick={handleToggle}>{children}</View>
      {renderKey % 2 === 0 ? (
        <NutuiPopup
          key="popup-even"
          visible={visible}
          onClose={handleClose}
          closeOnOverlayClick={false}
          className={`${PREFIX_CLS} ${className || ''}`}
          style={style}
          position={position}
          {...rest}
        >
          <View className="popup-content" onClick={(e) => e.stopPropagation()}>
            {content}
          </View>
          {footer && (
            <View
              className="popup-footer-wrap"
              onClick={(e) => e.stopPropagation()}
            >
              <View className="popup-footer">{footer}</View>
            </View>
          )}
          {showSafeArea && <SafeArea position="bottom" />}
        </NutuiPopup>
      ) : (
        <NutuiPopup
          key="popup-odd"
          visible={visible}
          onClose={handleClose}
          closeOnOverlayClick={false}
          className={`${PREFIX_CLS} ${className || ''}`}
          style={style}
          position={position}
          {...rest}
        >
          <View className="popup-content" onClick={(e) => e.stopPropagation()}>
            {content}
          </View>
          {footer && (
            <View
              className="popup-footer-wrap"
              onClick={(e) => e.stopPropagation()}
            >
              <View className="popup-footer">{footer}</View>
            </View>
          )}
          {showSafeArea && <SafeArea position="bottom" />}
        </NutuiPopup>
      )}
    </>
  );
};

export default forwardRef(Popup);
